package com.xtwroot.android.photogallery;

import android.util.Log;

import com.lzy.okgo.OkGo;
import com.xtwroot.android.photogallery.request.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.*;

/********************************************************************************
 * using for:
 * 丁酉鸡年正月 2017/02/21 20:43
 * @author 西唐王, xtwyzh@gmail.com,xtwroot.com
 * xtwroot Copyrights (c) 2017. All rights reserved.
 ********************************************************************************/
public class FlickrFetchr
{

    private static final String TAG = "FlickeFetchr";

    public byte[] getUrlBytes(String urlSpec) throws IOException
    {

        URL url = new URL(urlSpec);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();

        try
        {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = connection.getInputStream();

            if(connection.getResponseCode() != HttpURLConnection.HTTP_OK)
            {
                throw new IOException(connection.getResponseMessage() + ":with " + urlSpec);
            }

            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while((bytesRead = in.read(buffer)) > 0)
            {
                out.write(buffer,0,bytesRead);
            }
            out.close();
            return out.toByteArray();
        }
        finally
        {
            connection.disconnect();
        }
    }

    public String getUrlString(String urlSpac) throws IOException
    {
        return new String(getUrlBytes(urlSpac));
    }

    public static String createGetRequest(String url,RequestParams params){
        StringBuilder urlBuilder = new StringBuilder(url).append("?");
        if(params != null){
            for(Map.Entry<String,String> entry : params.urlParams.entrySet()){
                urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        return
                urlBuilder.substring(0,urlBuilder.length() - 1);
    }

    public List<GalleryItem> searchPhotos(String query)
    {
        return downloadGalleryItems(query,null);
    }

    public List<GalleryItem> fetchPhotos()
    {
        return downloadGalleryItems(null,null);
    }

    public List<GalleryItem> downloadGalleryItems(String tag1, String tag2)
    {

        List<GalleryItem> items = new ArrayList<>();

        try
        {
            /*
            String url = Uri.parse("https://api.flickr.com/services/rest/")
                    .buildUpon()
                    .appendQueryParameter("method","flickr.photos.getRecent")
                    .appendQueryParameter("api_key",API_KEY)
                    .appendQueryParameter("format","json")
                    .appendQueryParameter("nojsoncallback","1")
                    .appendQueryParameter("extras","url_s")
                    .build().toString();
            */
            if(tag1 == null)
                tag1 = "植物";
            if(tag2 == null)
                tag2 = "全部";

            RequestParams params = new RequestParams()
                    .put("pn","0")
                    .put("rn","100")
                    .put("tag1",tag1)
                    .put("tag2",tag2)
                    .put("ie","utf8");


            Response response = OkGo.get(createGetRequest("http://image.baidu.com/channel/listjson",params))
                    .tag(this)
                    .execute();


            //String jsonString = getUrlString(url);
            String jsonString = response.body().string();
            Log.i(TAG,"Received JSON: " + jsonString);
            JSONObject jsonBody = new JSONObject(jsonString);
            parseItems(items,jsonBody);
        }
        catch (IOException ioe)
        {
            Log.e(TAG,"Failed to fetch items",ioe);
        } catch (JSONException e) {
            Log.e(TAG,"Failed to parse JSON",e);
        }

        return items;
    }

    private void parseItems(List<GalleryItem> items,JSONObject jsonBody) throws IOException,JSONException
    {
        JSONArray photoJsonArray = jsonBody.getJSONArray("data");

        for(int i = 0;i < photoJsonArray.length() - 2;++i)
        {
            JSONObject photoJsonObject = photoJsonArray.getJSONObject(i);

            GalleryItem item = new GalleryItem();
            if(photoJsonObject.has("id"))
                item.setId(photoJsonObject.getString("id"));
            if(photoJsonObject.has("desc"))
                item.setCaption(photoJsonObject.getString("desc"));
            if(photoJsonObject.has("thumbnail_url"))
                item.setUrl(photoJsonObject.getString("thumbnail_url"));
            if(photoJsonObject.has("from_url"))
                item.setOwner(photoJsonObject.getString("from_url"));

            items.add(item);
        }

        Log.i(TAG,String.valueOf(items.size()));

    }

}
